package com.haidechizi.fastadmin.modules.sys.controller;


import com.haidechizi.fastadmin.common.annotation.OperateLog;
import com.haidechizi.fastadmin.common.base.AbstractController;
import com.haidechizi.fastadmin.common.exception.BusinessException;
import com.haidechizi.fastadmin.common.utils.Constant;
import com.haidechizi.fastadmin.common.utils.Response;
import com.haidechizi.fastadmin.common.validator.ValidatorUtils;
import com.haidechizi.fastadmin.modules.sys.entity.SysDict;
import com.haidechizi.fastadmin.modules.sys.entity.SysMenu;
import com.haidechizi.fastadmin.modules.sys.service.SysDictService;
import com.haidechizi.fastadmin.modules.sys.service.SysMenuService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 系统菜单
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends AbstractController {

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysDictService sysDictService;

    /**
     * 导航菜单
     */
    @RequestMapping("/nav")
    public Response nav() {
        List<SysMenu> menuList = sysMenuService.getUserMenuList(getUserId());
        // 增加隐藏标识，显示菜单时，删除隐藏的菜单
        Iterator<SysMenu> iterator = menuList.iterator();
        while (iterator.hasNext()) {
            SysMenu sysMenu = iterator.next();
            // 隐藏
            if (0 == sysMenu.getShowType()) {
                iterator.remove();
            }
        }
        return Response.ok().put("menuList", menuList);
    }

    /**
     * 所有菜单列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:menu:list")
    public List<SysMenu> list() {
        List<SysMenu> menuList = sysMenuService.selectList(null);
        for (SysMenu sysMenu : menuList) {
            // 获取ParentName
            SysMenu parentMenuEntity = sysMenuService.selectById(sysMenu.getParentId());
            if (parentMenuEntity != null) {
                sysMenu.setParentName(parentMenuEntity.getName());
            }
        }

        return menuList;
    }

    /**
     * 选择菜单(添加、修改菜单)
     */
    @RequestMapping("/select")
    @RequiresPermissions("sys:menu:select")
    public Response select() {
        //查询列表数据
        List<SysMenu> menuList = sysMenuService.queryNotButtonList();

        //添加虚拟顶级菜单
        SysMenu root = new SysMenu();
        root.setMenuId(0L);
        root.setName("一级菜单");
        root.setParentId(-1L);
        root.setOpen(true);
        menuList.add(root);

        return Response.ok().put("menuList", menuList);
    }

    /**
     * 菜单信息
     */
    @RequestMapping("/info/{menuId}")
    @RequiresPermissions("sys:menu:info")
    public Response info(@PathVariable("menuId") Long menuId) {
        SysMenu menu = sysMenuService.selectById(menuId);
        return Response.ok().put("menu", menu);
    }

    /**
     * 保存
     */
    @OperateLog("保存菜单")
    @RequestMapping("/save")
    @RequiresPermissions("sys:menu:save")
    public Response save(@RequestBody SysMenu menu) {
        // 校验必填参数
        ValidatorUtils.validateEntity(menu);
        //校验分类参数
        verifyForm(menu);

        sysMenuService.insert(menu);

        return Response.ok();
    }

    /**
     * 修改
     */
    @OperateLog("修改菜单")
    @RequestMapping("/update")
    @RequiresPermissions("sys:menu:update")
    public Response update(@RequestBody SysMenu menu) {
        // 校验必填参数
        ValidatorUtils.validateEntity(menu);
        //校验分类参数
        verifyForm(menu);

        sysMenuService.updateById(menu);

        return Response.ok();
    }

    /**
     * 删除
     */
    @OperateLog("删除菜单")
    @RequestMapping("/delete")
    @RequiresPermissions("sys:menu:delete")
    public Response delete(long menuId) {
        //判断是否有子菜单或按钮
        List<SysMenu> menuList = sysMenuService.queryListParentId(menuId);
        if (CollectionUtils.isNotEmpty(menuList)) {
            // 只有超级管理员才能删除父级菜单
            if (getUserId() != Constant.SUPER_ADMIN) {
                return Response.error("请先删除子菜单或按钮");
            }
            // 删除子菜单
            for (SysMenu menu : menuList) {
                sysMenuService.deleteChild(menu.getMenuId());
            }
        }
        sysMenuService.delete(menuId);
        return Response.ok();
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(SysMenu menu) {
        //菜单
        if (menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (StringUtils.isBlank(menu.getUrl())) {
                throw new BusinessException("菜单URL不能为空");
            }
        }

        //上级菜单类型
        int parentType = Constant.MenuType.CATALOG.getValue();
        // 0是一个虚拟目录
        if (menu.getParentId() != 0) {
            // 获取上级菜单类型
            SysMenu parentMenu = sysMenuService.selectById(menu.getParentId());
            parentType = parentMenu.getType();
        }

        //目录、菜单
        if (menu.getType() == Constant.MenuType.CATALOG.getValue() ||
                menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (parentType != Constant.MenuType.CATALOG.getValue()) {
                throw new BusinessException("上级菜单只能为目录类型");
            }
            return;
        }

        //按钮
        if (menu.getType() == Constant.MenuType.BUTTON.getValue()) {
            if (parentType != Constant.MenuType.MENU.getValue()) {
                throw new BusinessException("上级菜单只能为菜单类型");
            }
        }
    }

    /**
     * 获取字典列表(初始化select、checkbox、radio)
     */
    @RequiresPermissions("test:demo:list")
    @RequestMapping(value = "dictConfig")
    public Response dictConfig() {
        List<SysDict> showTypeList = sysDictService.queryDictByType("show_type");
        return Response.ok()
                .put("showTypeList", showTypeList);
    }


    /**
     * 获取字典Map(初始化字典数据，将code转成value)
     */
    @RequiresPermissions("test:demo:list")
    @RequestMapping(value = "dictMap")
    public Response dictMap() {
        Map<String, String> showTypeMap = sysDictService.queryDictMapByType("show_type");
        return Response.ok()
                .put("showTypeMap", showTypeMap);
    }
}
